package top100.backtrack;

import java.util.*;

/**
 * @Author ZhangCuirong
 * @Date 2025/7/16 14:24
 * @description: 给定一个可包含重复数字的序列 nums ，按任意顺序 返回所有不重复的全排列。
 * <p>
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * 输入：nums = [1,1,2]
 * 输出：
 * [[1,1,2],
 * [1,2,1],
 * [2,1,1]]
 * 示例 2：
 * <p>
 * 输入：nums = [1,2,3]
 * 输出：[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
 * <p>
 * <p>
 * 提示：
 * <p>
 * 1 <= nums.length <= 8
 * -10 <= nums[i] <= 10
 */
public class Solution47 {
    public void backtrack(int[] nums, LinkedList<Integer> path, List<List<Integer>> res, boolean[] used) {
        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (i>0 && nums[i] == nums[i-1] &&used[i-1] == true) {
                continue;
            }
            if(used[i]==false){
                path.addLast(nums[i]);
                used[i] = true;
                backtrack(nums, path, res,used);
                used[i] = false;
                path.removeLast();
            }
        }
    }
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        boolean used[] = new boolean[nums.length];
        backtrack(nums, new LinkedList<>(), res,used);
        return res;
    }

    public static void main(String[] args) {
        Solution47 solution = new Solution47();
        List<List<Integer>> res = solution.permuteUnique(new int[]{1, 1, 2});
        System.out.println(res);
    }
}
